﻿using System;
using System.IO;
using System.Threading;
using UnityEngine;
using UnityEngine.Networking;
using xuni;

namespace xres
{

    public class CheckCrc32Action : BaseAsyncAction
    {

        public const string Err_Crc32 = "Err_Copy";


        string _filePath = "";
        uint _crc32;
        float _prg;


        public bool IsOk { get; private set; }

        public float CheckProgress()
        {
            switch (_state)
            {
            case BaseAsyncActionState.Init:
                return 0;

            case "InRun":
                return _prg;
            }

            return 1;
        }

        public void Check(string filePath, uint crc32)
        {
            //对象可用于重复执行copy任务
            switch (_state)
            {
            case BaseAsyncActionState.Init:
            case BaseAsyncActionState.Finish:
                break;

            default:
                return;
            }

            _filePath = filePath;
            _crc32 = crc32;
            _prg = 0;
            IsOk = false;

            _state = "InRun";

            ThreadPool.QueueUserWorkItem(RunOnThread);
        }

        void RunOnThread(object state)
        {
            var errMsg = "";
            var crc = 0;
            try
            {
                var crc32 = Crc32Utils.FileCrc32(_filePath, null, null, ref _prg);
                crc = (int)crc32;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                Debug.Log($"crc32 fail: {errMsg}");
            }

            MainThreadSync.QueueOnMainThread(OnComplete_Crc32, crc, errMsg);
        }

        void OnComplete_Crc32(UserData userData)
        {
            var errMsg = userData.s;
            var crc32 = (uint)userData.i;

            if (!string.IsNullOrEmpty(errMsg))
            {
                SetError(Err_Crc32, errMsg);
                SetFinishAndNotify(ErrMsg);
            }
            else
            {
                IsOk = (crc32 == _crc32);

                SetError("", "");
                SetFinishAndNotify("");
            }
        }


    } //end of class


}


